<?php

class SongController extends Controller
{
    private $_model;
    private $_assetsUrl;
    public $debug = true;

    public function actionIndex()
    {
        $criteria = new CDbCriteria(array('condition' => 'is_validated = 1 AND status = 1'));

        $dataProvider = new CActiveDataProvider('Song', array(
            'criteria' => $criteria,
        ));
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function getAssetsUrl()
    {
        if ($this->_assetsUrl === null) {
            $assetsPath = Yii::getPathOfAlias('application.resources.chord');

            // We need to republish the assets if debug mode is enabled.
            if ($this->debug === true)
                $this->_assetsUrl = Yii::app()->getAssetManager()->publish($assetsPath, false, -1, true);
            else
                $this->_assetsUrl = Yii::app()->getAssetManager()->publish($assetsPath);
        }

        return $this->_assetsUrl;
    }

    public function registerScripts()
    {
        // Get the url to the module assets
        $assetsUrl = $this->getAssetsUrl();

        // Register the necessary scripts
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('jquery');
        $cs->registerCoreScript('jquery.ui');
        $redmond = Yii::app()->assetManager->publish(Yii::app()->basePath . '/resources/jquery.ui/ui-lightness/');
        Yii::app()->clientScript->registerCssFile($redmond . '/jquery-ui-1.8.20.custom.css', 'screen');
        $cs->registerScriptFile($assetsUrl . '/jquery.ui.touch-punch.js');
        $cs->registerScriptFile($assetsUrl . '/jquery_chords.js');
        $cs->registerScriptFile($assetsUrl . '/jquery.transposer.js');
        $cs->registerCssFile($assetsUrl . '/chord.css');


    }

    public function actionView()
    {
        $this->registerScripts();
        $model = $this->loadModel();
        $model->view++;
        $model->update(array('view'));
        $comment = $this->newComment($model);

        $this->render('view', array('model' => $model, 'comment' => $comment));
    }

    public function actionPost()
    {
        if (Yii::app()->user->isGuest) {
            Yii::app()->user->loginRequired();
        }
        $model = new Song;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Song'])) {
            $model->attributes = $_POST['Song'];
            $model->is_validated = 2;
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('post', array(
            'model' => $model,
        ));
    }

    public function actionRate($id)
    {
        $song = Song::model()->findByPk($id);
        if (Yii::app()->user->isGuest) {
            echo json_encode(array('login' => 1));
            exit;
        }
        if (isset($_POST) && $_POST['marks']) {
            if (!$song->ownrateCount) {

                $rate = new SongRate();
                $rate->user_id = Yii::app()->user->id;
                $rate->song_id = $song->id;
                $rate->rate_time = time();
                $rate->marks = (int)$_POST['marks'];
                if ($rate->save()) {
                    /*$video->refresh();
                    $ok = array('success'=>1,'star'=>'','av'=>' ('.$video->averrate.', '.$video->rateCount.')');
                    if($video->star){
                        for($i = 0;$i < $video->star;$i++){
                            $ok['star'] .= '<img src="/images/star.png"/>';
                        }
                    }*/
                    header('Content-Type:application/json');
                    echo json_encode(array('success' => 1));
                } else {
                    var_dump($rate->errors);
                }

            }
        }
    }

    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id'])) {
                $condition = '';
                $this->_model = Song::model()->findByPk($_GET['id'], $condition);
            }

            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }

        return $this->_model;
    }

    /**
     * @param $news News
     * @return Comments
     */
    protected function newComment($song)
    {
        $comment = new Comments;
        if (!Yii::app()->user->isGuest) {
            $comment->user_id = (int)Yii::app()->user->id;

        }
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'comments-form') {
            echo CActiveForm::validate($comment);
            Yii::app()->end();
        }
        if (isset($_POST['Comments'])) {
            $comment->attributes = $_POST['Comments'];
            if ($song->addComment($comment)) {
                Yii::app()->user->setFlash('commentSubmitted', 'Cảm ơn bạn đã bình luận.');
                $this->refresh();
            }
        }
        return $comment;
    }
}